package com.mo.xi.ge.info.bean

import android.os.Handler
import android.os.Looper
import com.google.gson.GsonBuilder
import com.google.gson.JsonObject
import com.mo.xi.ge.info.DaleInfoInstance
import com.mo.xi.ge.info.help.DataConstant
import com.mo.xi.ge.info.help.DeviceNetUtil
import com.mo.xi.ge.info.help.EncryptWrapper
import com.mo.xi.ge.info.help.versionCode
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.net.UnknownHostException
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

/**
 * date:2024/1/27
 **/
internal object DataNetWork {

    private val mhandle = Handler(Looper.getMainLooper())

    private const val COUNT = 3
    var mRetryCount = 0

    const val TYPE1 = "1000"
    const val TYPE2 = "2000"

    // 上传设备信息 type:1000 init,2000 device（AES加密）
    fun postInfo(type: String = TYPE2) {
        val ctx = DaleInfoInstance.INSTANCE.mContext ?: return
        DaleInfoInstance.INSTANCE.startLocation()
        Executors.newSingleThreadExecutor().execute {
            val aesKey = DaleInfoInstance.INSTANCE.aes
            var isSucess = true
            try {
                val gson = GsonBuilder().serializeNulls().create()
//                val pobkey = SecutyEncrypt.generateKey()
                val jsonStr = gson.toJson(DataInfoInstance.dataInfos(ctx, type))
                val dataJbj = JsonObject().also {
                    it.addProperty("idcode", type)
                    it.addProperty("dataRecord", EncryptWrapper.aesEncrpt(jsonStr, aesKey))
                }
                val body =
                    RequestBody.create("application/json".toMediaType(), gson.toJson(dataJbj))
                val response = mOkHttpClient.newCall(
                    Request.Builder().url(DataConstant.remoteUrl).post(body).build()
                ).execute()
                isSucess = response.isSuccessful
//                Log.d("debug_DeviceInfo", "deviceUpload: response = $response")
            } catch (e: Exception) {
                isSucess = e is UnknownHostException
                //                Log.e("debug_DeviceInfo", "deviceUpload: error = $e")
            }
            if (!isSucess && mRetryCount < COUNT) {
                mRetryCount++
                mhandle.post {
                    postInfo()
                }
            }
        }
    }

    private val mOkHttpClient by lazy {
        OkHttpClient.Builder().also {
            it.readTimeout(70000L, TimeUnit.MILLISECONDS)
                .writeTimeout(70000L, TimeUnit.MILLISECONDS)
                .connectTimeout(70000L, TimeUnit.MILLISECONDS)
                .addInterceptor(Interceptor { chain ->
                    val request = chain.request()
                    val builder = request.newBuilder()
                    builder.addHeader(
                        "release_metric",
                        DaleInfoInstance.INSTANCE.mContext?.versionCode()?.toString().orEmpty()
                    )
                    var tok = DaleInfoInstance.INSTANCE.getDalaToken().orEmpty()
                    builder.addHeader("tok", tok)
                    var uid = DaleInfoInstance.INSTANCE.usrId.orEmpty();
                    builder.addHeader("userid", uid)
                    builder.addHeader("Content-Type", "application/json")
                    builder.addHeader(
                        "packageName",
                        DaleInfoInstance.INSTANCE.mContext?.packageName.orEmpty()
                    )
                    builder.addHeader("genuineNetworkAddress", DeviceNetUtil.getMobileIp())
                    builder.addHeader("hiddenIdentification", DataConstant.mSecretid)
                    builder.method(request.method, request.body)
                    chain.proceed(builder.build())
                })
//            if (BuildConfig.DEBUG) {
//            it.addInterceptor(
//                LoggingInterceptor.Builder().setLevel(Level.BASIC)
//                    .log(Platform.INFO)
//                    .request("Request")
//                    .response("response")
//                    .build()
//            )
//            }
        }.build()
    }
}
